package top.psjj.mall.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.psjj.mall.exception.MallException;
import top.psjj.mall.exception.MallExceptionEnum;
import top.psjj.mall.mapper.UserMapper;
import top.psjj.mall.model.po.User;
import top.psjj.mall.service.api.UserService;
import top.psjj.mall.utils.MD5Utils;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ,readOnly = false,timeout =-1 )
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void register(String username, String password) {
        //检测用户名是否存在
        User user = userMapper.selectByName(username);
        if(user!=null){
            throw new MallException(MallExceptionEnum.EXISTS_NAME);
        }
        User regUser = new User();
        regUser.setUsername(username);
        regUser.setPassword(MD5Utils.getMD5Str(password));
        userMapper.insertSelective(regUser);
    }

    @Override
    public User login(String username, String password) {
        //根据用户名和密码查询
        User user = userMapper.selectByNameAndPwd(username,MD5Utils.getMD5Str(password));
        //如果用户不存在抛出登陆异常
        if(user==null){
            throw new MallException(MallExceptionEnum.LOGIN_FAIL);
        }
        return user;
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }
}
